import 'dart:convert';
import 'dart:io';

import 'package:fast_gbk/fast_gbk.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:sqflite_demo/model/Book.dart';
import 'package:sqflite_demo/model/Chapter.dart';
import '../helpers/database_helper.dart';


class BookProvider with ChangeNotifier {
  final DatabaseHelper _databaseHelper = DatabaseHelper();
  List<Book> _books = [];

  List<Book> get books => _books;

  BookProvider() {
    _fetchBooks();
  }

  Future<void> _fetchBooks() async {
    final result = await _databaseHelper.getBooks();
    _books = result.map((map) => Book.fromMap(map)).toList();
    notifyListeners(); // 通知 UI 层更新
  }

  // 外部使用的刷新方法。
  Future<void> refreshBooks() async {
    await _fetchBooks();
    notifyListeners();
  }

  Future<int> addBook(Map<String, dynamic> book) async {
    final id = await _databaseHelper.insertBook(book);
    await _fetchBooks(); // 重新加载数据
    return id;
  }

  Future<void> deleteBookAndChapter(int id) async {
    await _databaseHelper.deleteBookWithChapter(id);
    await _fetchBooks(); // 重新加载数据
  }

  // 将 convertFromTxt 整合到 BookProvider 中以实现状态管理
  Future<void> convertFromTxt() async {
    File? file = await _pickFile();
    if (file == null) return;

    final dbHelper = DatabaseHelper();

    var filename = file.path.split('/').last;
    filename = filename.split('.').sublist(0, filename.split('.').length - 1).join('.');
    final titleString = RegExp(r'(?<=《)[^》]+').firstMatch(filename)?.group(0) ?? filename;
    final authorString = RegExp(r'(?<=作者：).*').firstMatch(filename)?.group(0) ?? 'Unknown';

    // 插入书籍并获取书籍 ID
    int currentBook = await dbHelper.insertBook({'title': titleString, 'author': authorString});

    // 读取文件内容
    String content = await readFileWithEncoding(file);
    final patternStr = RegExp(
      r'^(?:(.+ +)|())(第[一二三四五六七八九十零〇百千万两0123456789]+[章卷]|卷[一二三四五六七八九十零〇百千万两0123456789]+|chap(?:ter)\.?|vol(?:ume)?\.?|book|bk)(?:(?: +.+)?|(?:\S.*)?)$',
      multiLine: true,
      caseSensitive: false,
    );

    // 分割文章内容
    List<String> sections = [];
    int lastMatchEnd = 0;

    for (final match in patternStr.allMatches(content)) {
      if (match.start > lastMatchEnd) {
        sections.add(content.substring(lastMatchEnd, match.start).trim());
      }
      String matchedSection = content.substring(match.start, match.end).trim();
      sections.add(matchedSection);
      lastMatchEnd = match.end;
    }

    if (lastMatchEnd < content.length) {
      sections.add(content.substring(lastMatchEnd).trim());
    }


    await dbHelper.insertChapter({'book_id': currentBook, 'title': "前言", 'content': sections[0]});

    List<Chapter> chapters = [];
    for (int i = 1; i < sections.length; i += 2) {
      if (i + 1 < sections.length) { // 确保不会越界
        chapters.add(Chapter(bookId: currentBook, title: sections[i], content: sections[i+1]));
      }
    }

    // 巨快越多越快
    await dbHelper.insertAllChapter(chapters);

    // 存储分割结果 单次操作太慢了
    // for (int i = 1; i < sections.length; i += 2) {
    //   if (i + 1 < sections.length) { // 确保不会越界
    //     await dbHelper.insertChapter({'book_id': currentBook, 'title': sections[i], 'content': sections[i + 1]});
    //   }
    // }

    // 刷新书籍列表
    await _fetchBooks();
  }

  Future<File?> _pickFile() async {
    // 打开文件选择器
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['txt'], // 只允许选择 .txt 文件
    );

    if (result != null) {
      String path = result.files.single.path!;
      File file = File(path); // 获取文件路径
      return file;
    } else {
      // 用户取消选择
      return null;
    }
  }

  Future<String> readFileWithEncoding(File file) async {
    final bytes = await file.readAsBytes();

    bool checkGarbled(String subContent) {
      final garbledPattern = RegExp(r'Õ|Ê|Ç|³|¾|Ð|Ó|Î|Á|É|�');

      final lines = subContent.split('\n');
      final sampleLines = lines.take(lines.length > 10 ? 10 : lines.length);
      return sampleLines.any((line) => garbledPattern.hasMatch(line));
    }

    // UTF-8 测试
    try {
      String contentUtf8 = utf8.decode(bytes, allowMalformed: true); // 使用 allowMalformed: true 来容忍一些格式错误的 UTF-8 序列
      if (!checkGarbled(contentUtf8)) {
        return contentUtf8;
      }
    } catch (e) {
      // 忽略 UTF-8 解码错误
    }

    // GBK 解码
    try {
      String contentGBK = gbk.decode(bytes, allowMalformed: true);
      if (!checkGarbled(contentGBK)) {
        return contentGBK;
      }
    } catch (e) {
      // 捕获并处理 GBK 解码错误
    }

    // 如果两种编码都失败，返回错误信息
    return '无法解码文件，可能是未知编码或文件损坏。';
  }
}